import React, { Component } from "react";
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import PropTypes from "prop-types";
import styles from "./index.less";


class EditorText extends Component {

    // props类型检查
    static propTypes = {
        //  监听选择
        onChange: PropTypes.func,
        // 获取选择值
        getSelectedValues: PropTypes.func,
        defaultValue: PropTypes.string
    };

    state = {
        editorState: EditorState.createEmpty()
    }

    componentDidMount() {
        const { defaultValue } = this.props;
        if (defaultValue && defaultValue !== 'null') {
            const contentBlock = htmlToDraft(defaultValue);
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            this.setState({ editorState });
            this.props.onChange(defaultValue);
        }

    }

    onEditorStateChange(editorState) {
        this.setState({
            editorState,
        });
        this.props.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())));
    }

    render() {
        return (
            <div className={styles.editorBox}>
                <Editor
                    editorState={this.state.editorState}
                    toolbarClassName="rdw-storybook-toolbar"
                    wrapperClassName="rdw-storybook-wrapper"
                    editorClassName="rdw-storybook-editor"
                    onEditorStateChange={this.onEditorStateChange.bind(this)}
                    toolbar={{
                        options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'remove', 'history', 'pagebreak'],
                        inline: { inDropdown: true },
                        list: { inDropdown: true },
                        textAlign: { inDropdown: true },
                        link: { inDropdown: true },
                        history: { inDropdown: true },
                    }}
                />
            </div>
        );
    }
}

export default EditorText;